import axios from 'axios'
import Vue from 'vue'
export function excel(url, data, method) {
	return new Promise((resolve, reject) => {
		axios({
			method: method,
			url: Vue.prototype.$URL + url,
			data,
			responseType: 'blob',
			header: {
				// 'token': "eyJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50IjoiMjk0MzQwNTEwNiIsImlhdCI6MTc1MDE0MjA4NCwiZXhwIjoxNzgxNjc4MDg0fQ.-zbQx1OKvLHP3O8Q_ScJaojNg-S8F4noRiVqmBWXQ8k"
				'token': uni.getStorageSync('token')
			}
		}).then(response => {
			console.log(response);
			// 从响应头中提取文件名
			const fileName = getFileNameFromResponse(response);
			const blob2 = new Blob([response.data], {
				type: 'application/vnd.openxmlformats - officedocument.spreadsheetml.sheet'
			})

			// 创建下载链接并触发下载
			// createDownloadLink(blob2, fileName);
			createDownloadLink(blob2, fileName);

			resolve({
				success: true,
				fileName
			});

		})
	})
}

// 从响应头中提取文件名
function getFileNameFromResponse(response) {
	const contentDisposition = response.headers['content-disposition'] || '';
	const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
	if (match) {
		return decodeURIComponent(match[1].replace(/['"]/g, ''));
	}
	return '下载文件.xlsx';
}

// 创建下载链接并模拟点击
function createDownloadLink(blob, fileName) {
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = fileName;
	a.style.display = 'none'; // 隐藏链接元素

	document.body.appendChild(a);
	a.click(); // 模拟点击下载

	// 清理资源（防止内存泄漏）
	setTimeout(() => {
		document.body.removeChild(a);
		URL.revokeObjectURL(url);
	}, 0);
}